package com.atguigu.gmall.realtime.dim.app;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.edu.realtime.common.base.BaseApp;
import com.atguigu.edu.realtime.common.bean.TableProcessDim;
import com.atguigu.edu.realtime.common.constant.Constant;
import com.atguigu.edu.realtime.common.util.FlinkSourceUtil;
import com.atguigu.edu.realtime.common.util.HBaseUtil;
import com.atguigu.gmall.realtime.dim.function.DimSinkFunction;
import com.atguigu.gmall.realtime.dim.function.TableProcessFunction;
import com.ververica.cdc.connectors.mysql.source.MySqlSource;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.restartstrategy.RestartStrategies;
import org.apache.flink.api.common.state.MapStateDescriptor;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.configuration.RestOptions;
import org.apache.flink.streaming.api.CheckpointingMode;
import org.apache.flink.streaming.api.datastream.BroadcastStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.CheckpointConfig;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.util.Collector;
import org.apache.hadoop.hbase.client.Connection;

public class Dimapp extends BaseApp {
    public static void main(String[] args) {
        new Dimapp().start(5678,4,"edu_dim", Constant.TOPIC_DB);
    }

    @Override
    public void handle(StreamExecutionEnvironment env, DataStreamSource<String> kafkaStrDS) {
        //TODO 1.对流中数据进行类型转换并进行简单的ETL jsonStr -> jsonObj
        SingleOutputStreamOperator<JSONObject> processJsonDS = etl(kafkaStrDS);
        //processJsonDS.print();
        //{"database":"edu","xid":76853,"data":{"birthday":"1971-06-13","create_time":"2024-11-13 00:00:00","login_name":"g46hpw","user_level":"1","phone_num":"13777499876","id":1213,"email":"g46hpw@263.net"},"commit":true,"type":"insert","table":"user_info","ts":1731484299}
        //TODO 2.使用FlinkCDC读取配置表的信息
        SingleOutputStreamOperator<TableProcessDim> beanDS = readTableProcess(env);
        //beanDS.print();
        //TableProcessDim(sourceTable=user_chapter_process, sinkTable=dim_user_chapter_process, sinkColumns=id,course_id,chapter_id,user_id,position_sec,create_time, sinkFamily=info, sinkRowKey=id, op=r)
        //TODO 3.根据配置表中的配置信息在HBase中建表或者删表
        beanDS = createHBaseTable(beanDS);
        //beanDS.print();
        //TODO 4.广播配置流并和主流进行关联
        SingleOutputStreamOperator<Tuple2<JSONObject, TableProcessDim>> connectProcessDS = connect(processJsonDS, beanDS);

        //TODO 5.将维度数据提交到HBase
        write2HBase(connectProcessDS);
    }

    private static void write2HBase(SingleOutputStreamOperator<Tuple2<JSONObject, TableProcessDim>> connectProcessDS) {
        connectProcessDS.addSink(new DimSinkFunction());
    }

    private static SingleOutputStreamOperator<Tuple2<JSONObject, TableProcessDim>> connect(SingleOutputStreamOperator<JSONObject> processJsonDS, SingleOutputStreamOperator<TableProcessDim> beanDS) {
        //4.1 广播配置流
        MapStateDescriptor<String, TableProcessDim> mapStateDescriptor = new MapStateDescriptor<String, TableProcessDim>("mapStateDesc", String.class, TableProcessDim.class);
        BroadcastStream<TableProcessDim> broadcastDS = beanDS.broadcast(mapStateDescriptor);
        //4.2 将主流业务数据和广播流配置信息进行关联
        //4.3 对关联数据进行处理
        SingleOutputStreamOperator<Tuple2<JSONObject, TableProcessDim>> connectProcessDS = processJsonDS.connect(broadcastDS).process(new TableProcessFunction(mapStateDescriptor));
        connectProcessDS.print("connect");
        return connectProcessDS;
    }

    private static SingleOutputStreamOperator<TableProcessDim> createHBaseTable(SingleOutputStreamOperator<TableProcessDim> beanDS) {
        beanDS = beanDS.map(new RichMapFunction<TableProcessDim, TableProcessDim>() {
            private Connection hBaseConnection;
            @Override
            public void open(Configuration parameters) throws Exception {
                hBaseConnection = HBaseUtil.getHBaseConnection();
                System.out.println("获取hbase连接");
            }

            @Override
            public void close() throws Exception {
                HBaseUtil.closeHBaseConnection(hBaseConnection);
            }

            @Override
            public TableProcessDim map(TableProcessDim value) throws Exception {
                String op = value.getOp();
                String sinkFamily = value.getSinkFamily();
                String[] families = sinkFamily.split(",");
                if("c".equals(op)||"r".equals(op)){
                    HBaseUtil.createHBaseTable(hBaseConnection,Constant.HBASE_NAMESPACE, value.getSinkTable(),families);
                } else if ("d".equals(op)) {
                    HBaseUtil.dropHBaseTable(hBaseConnection,Constant.HBASE_NAMESPACE, value.getSinkTable());
                } else if ("u".equals(op)) {
                    HBaseUtil.dropHBaseTable(hBaseConnection,Constant.HBASE_NAMESPACE, value.getSinkTable());
                    HBaseUtil.createHBaseTable(hBaseConnection,Constant.HBASE_NAMESPACE, value.getSinkTable(),families);
                }
                return value;
            }
        });
        return beanDS;
    }

    private static SingleOutputStreamOperator<TableProcessDim> readTableProcess(StreamExecutionEnvironment env) {
        MySqlSource<String> mySqlSource = FlinkSourceUtil.getMySqlSource("edu_config", "table_process_dim");
        DataStreamSource<String> mysqlStrDS = env.fromSource(mySqlSource, WatermarkStrategy.noWatermarks(), "mysql_source");
        //mysqlStrDS.print();
        //2.1 对配置流中数据进行类型转换 jsonStr -> 实体类对象
        SingleOutputStreamOperator<TableProcessDim> beanDS = mysqlStrDS.map(new MapFunction<String, TableProcessDim>() {
            @Override
            public TableProcessDim map(String value) throws Exception {
                JSONObject jsonObject = JSONObject.parseObject(value);
                String op = jsonObject.getString("op");
                TableProcessDim tableProcessDim = null;
                if ("d".equals(op)) {
                    tableProcessDim = jsonObject.getObject("before", TableProcessDim.class);
                } else {
                    tableProcessDim = jsonObject.getObject("after", TableProcessDim.class);
                }
                tableProcessDim.setOp(op);
                return tableProcessDim;
            }
        });
        return beanDS;
    }

    private static SingleOutputStreamOperator<JSONObject> etl(DataStreamSource<String> kafkaStrDS) {
        SingleOutputStreamOperator<JSONObject> processJsonDS
                = kafkaStrDS.process(new ProcessFunction<String, JSONObject>() {
            @Override
            public void processElement(String s, ProcessFunction<String, JSONObject>.Context context, Collector<JSONObject> collector) throws Exception {
                try {
                    JSONObject jsonObject = JSONObject.parseObject(s);
                    String type = jsonObject.getString("type");
                    String database = jsonObject.getString("database");
                    String data = jsonObject.getString("data");
                    if ("edu".equals(database)
                            && ("bootstrap-insert".equals(type) || "insert".equals(type) || "update".equals(type) || "delete".equals(type))
                            && data != null && data.length() > 2
                    ) {
                        collector.collect(jsonObject);
                    }
                } catch (Exception e) {
                    System.out.println("属于脏数据");
                }
            }
        });
        return processJsonDS;
    }
}
